#include "wb2_led.h"

#include <bl_gpio.h>
#include <string.h>
#include <stdint.h>
#include <bl602.h>
#include <glb_reg.h>
#include <stdio.h>

/**
 * bit0: b
 * bit1: g
 * bit2: r
 */
static uint8_t rgb = 0;


void update_status(uint8_t pin, uint8_t data)
{
    int mask = 0;
    switch (pin)
    {
        case PIN_R:
            mask = 2;
            break;
        case PIN_G:
            mask = 1;
            break;
        case PIN_B:
            mask = 0;
            break;
    }
    if (data) {
        rgb |= 1 << mask;
    }
    else {
        rgb &= ~(1 << mask);
    }
}

static int get_pin(const char* led)
{
    int pin = -1;
    if (strcmp(led, "r") == 0) {
        pin = PIN_R;
    }
    else if (strcmp(led, "g") == 0) {
        pin = PIN_G;
    }
    else if (strcmp(led, "b") == 0) {
        pin = PIN_B;
    }
    return pin;
}

/**
 * 打开指定颜色的灯
 * @param  led     r、g、b
 */
void wb2_led_open(const char* led)
{
    if (get_pin(led) != -1) {
        update_status(get_pin(led), 1);
        bl_gpio_output_set(get_pin(led), 1);
    }

}
/**
 * 关闭指定颜色的灯
 * @param  led     r、g、b
 */
void wb2_led_close(const char* led)
{
    if (get_pin(led) != -1) {
        update_status(get_pin(led), 0);
        bl_gpio_output_set(get_pin(led), 0);
    }
}

/**
 * 获取指定灯的状态
 * @param  led     r、g、b
 * @return int 0 close，1open
 */
uint8_t wb2_led_status(const char* led)
{
    int mask = 0;
    switch (get_pin(led))
    {
        case PIN_R:
            mask = 2;
            break;
        case PIN_G:
            mask = 1;
            break;
        case PIN_B:
            mask = 0;
            break;
    }
    return (rgb >> mask) & 0x1;
}

void wb2_led_init(uint8_t pin)
{
    bl_gpio_enable_output(pin, 0, 1);
    bl_gpio_output_set(pin, 0);
}